package cuid.sc20.laboratory.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

public class CookieUtils {
    public static Cookie getCookie(HttpServletRequest request, String key){
        Cookie[] cookies = request.getCookies();
        if (Objects.isNull(cookies) || cookies.length == 0){
            return null;
        }
        for (Cookie cookie : cookies) {
            if (Objects.equals(key,cookie.getName())){
                return cookie;
            }
        }
        return null;
    }
    public static void setCookie(HttpServletResponse response, String key, String value, Integer expireTime){
        Cookie cookie = new Cookie(key,value);
        cookie.setPath("/"); //-- 设置Cookie的Path，只有Path为/的Cookie在一级域名下，才可以被所有的二级域名访问！
        if(expireTime!=null) cookie.setMaxAge(expireTime);
        response.addCookie(cookie);
    }
}